package com.his.his_system.common.filter;



import cn.hutool.extra.spring.SpringUtil;
import com.his.his_system.domain.DzmHisAuthGroup;
import com.his.his_system.domain.DzmHisMember;
import com.his.his_system.mapper.DzmHisAuthGroupMapper;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * 动态权限判断
 * 在这里可以进行菜单或者说接口的权限校验
 */
@Component
public class MenuAccessDecisionManager implements AccessDecisionManager {


    @Autowired
    private DzmHisAuthGroupMapper authGroupMapper;

    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {

//        鉴权
        System.out.println("鉴权");
        if(collection == null){
            return;
        }

        Object principal = authentication.getPrincipal();
        if(principal instanceof String){
            throw new BadCredentialsException("未登录");
        }

        List<DzmHisAuthGroup> roleList=null;
        for (ConfigAttribute configAttribute : collection) {
            // 当前请求需要的权限
            String needRole = configAttribute.getAttribute();
//            if ("ROLE_LOGIN".equals(needRole)) {
//                return;
//            }

            // 当前用户所具有的权限
            if(roleList==null){
                LinkedHashMap<String, Object> curUser = (LinkedHashMap<String, Object>) principal;
//                DzmHisMember loginUser =(DzmHisMember) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
                roleList = authGroupMapper.findRolesByUserId((Integer) curUser.get("uid"));
            }
            for (GrantedAuthority grantedAuthority : roleList) {
                // 包含其中一个角色即可访问
                if (grantedAuthority.getAuthority().equals(needRole)) {
                    return;
                }
            }

        }
        throw new AccessDeniedException("SimpleGrantedAuthority!!");
    }

    @Override
    public boolean supports(ConfigAttribute attribute) {
        return false;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return false;
    }
}
